import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import axios from 'axios'

Vue.use(ElementUI, { size: 'small' })
Vue.config.productionTip = false

// 配置 axios
axios.defaults.baseURL = 'http://localhost:3000/api'
Vue.prototype.$http = axios

// 请求拦截器
axios.interceptors.request.use(
  config => {
    NProgress.start()
    // 在请求头中添加token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    NProgress.done()
    return Promise.reject(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  response => {
    NProgress.done()
    return response
  },
  error => {
    NProgress.done()
    const { status } = error.response
    if (status === 401) {
      // 未授权，清除token并跳转到登录页
      localStorage.removeItem('token')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
